'use client';

import { useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/contexts/auth-context';
import { LoadingScreen } from '@/components/loading-screen';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Lock, LogIn } from 'lucide-react';

interface ProtectedRouteProps {
  children: React.ReactNode;
  redirectTo?: string;
  showLoginPrompt?: boolean;
  customMessage?: string;
}

export function ProtectedRoute({ 
  children, 
  redirectTo = '/auth/login',
  showLoginPrompt = true,
  customMessage 
}: ProtectedRouteProps) {
  const { isAuthenticated, isLoading } = useAuth();
  const router = useRouter();

  useEffect(() => {
    if (!isLoading && !isAuthenticated && !showLoginPrompt) {
      // 保存当前页面路径，登录后可以返回
      const currentPath = window.location.pathname + window.location.search;
      localStorage.setItem('redirectAfterLogin', currentPath);
      router.push(redirectTo);
    }
  }, [isAuthenticated, isLoading, router, redirectTo, showLoginPrompt]);

  // 显示加载状态
  if (isLoading) {
    return <LoadingScreen />;
  }

  // 未登录且需要显示登录提示
  if (!isAuthenticated && showLoginPrompt) {
    return (
      <div className="min-h-screen pt-20 flex items-center justify-center">
        <Card className="w-full max-w-md bg-gray-800/50 border-gray-700">
          <CardHeader className="text-center">
            <div className="mx-auto w-12 h-12 bg-blue-500/20 rounded-full flex items-center justify-center mb-4">
              <Lock className="w-6 h-6 text-blue-400" />
            </div>
            <CardTitle className="text-white text-xl">
              需要登录访问
            </CardTitle>
          </CardHeader>
          <CardContent className="text-center space-y-4">
            <p className="text-gray-300">
              {customMessage || '您需要登录后才能访问此页面'}
            </p>
            <div className="space-y-3">
              <Button 
                onClick={() => {
                  // 保存当前页面路径
                  const currentPath = window.location.pathname + window.location.search;
                  localStorage.setItem('redirectAfterLogin', currentPath);
                  router.push(redirectTo);
                }}
                className="w-full bg-gradient-to-r from-blue-500 to-purple-500 hover:from-blue-600 hover:to-purple-600"
              >
                <LogIn className="w-4 h-4 mr-2" />
                立即登录
              </Button>
              <Button 
                variant="outline" 
                onClick={() => router.push('/')}
                className="w-full border-gray-600 text-gray-300 hover:bg-gray-700"
              >
                返回首页
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  // 未登录且不显示提示（直接重定向）
  if (!isAuthenticated && !showLoginPrompt) {
    return <LoadingScreen />;
  }

  // 已登录，显示受保护的内容
  return <>{children}</>;
}

// 高阶组件版本，用于包装页面组件
export function withAuth<P extends object>(
  Component: React.ComponentType<P>,
  options?: {
    redirectTo?: string;
    showLoginPrompt?: boolean;
    customMessage?: string;
  }
) {
  return function AuthenticatedComponent(props: P) {
    return (
      <ProtectedRoute {...options}>
        <Component {...props} />
      </ProtectedRoute>
    );
  };
}

export default ProtectedRoute;